﻿using Ledict.ConditionExtract.Base;
using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.BLL.WorkProcess;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.Model;
using Ledict.Utility.Helper;
using Ledict.Utility.Msg;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Ledict.Utility.Frm;
using Ledict.ConditionExtract.DAL;

namespace Ledict.ConditionExtract.Frm.DataProcess
{
    public partial class CrimeDataProcessNew : BaseForm
    {
        #region 界面初始化

        //静态锁
        private static readonly object Lock = new object();

        static CrimeDataProcessNew _default;
        public static CrimeDataProcessNew Default
        {
            get
            {
                if (_default == null || _default.IsDisposed)
                {
                    lock (Lock)
                    {
                        if (_default == null || _default.IsDisposed)
                        {
                            _default = new CrimeDataProcessNew();
                        }
                    }

                }
                return _default;
            }
        }
        public CrimeDataProcessNew()
        {
            InitializeComponent();
            NowProcessNode.TreeView.AfterExpand += new TreeViewEventHandler(NowProcessNode_AfterExpand);
            NowProcessNode.TreeView.AfterCollapse += TreeView_AfterCollapse;
        }

        private void TreeView_AfterCollapse(object sender, TreeViewEventArgs e)
        {
            //throw new NotImplementedException();
        }

        #endregion

        TreeDataBLL trbll = new TreeDataBLL();
        CaseCauseBLL casecausebLL = new CaseCauseBLL();
        Express_WordBLL wordbll = new Express_WordBLL();
        Express_AddElement addelementbll = new Express_AddElement();
        NewIDBLL newid = new NewIDBLL();
        ExpressGroupSituationBLL expresitu = new ExpressGroupSituationBLL();
        RegexParse.RegexParse getregex = new RegexParse.RegexParse();
        WorkThread_Public work = new WorkThread_Public();
        WordBankKeyWordsBLL wordbankkeywordsbll = new WordBankKeyWordsBLL();
        Express_WordBankRelBLL express_wordbankrelbll = new Express_WordBankRelBLL();
        WordBankBLL wordbankbll = new WordBankBLL();
        DataProcess_EditNode dataprocess_editnode = new DataProcess_EditNode();
        Express_MatchSituationBLL express_matchsituationbll = new Express_MatchSituationBLL();

        #region 共有变量

        private string sort = "";
        private string IsASC = "";
        private string SelectText = "";
        private string SelectWBK_ID = "";
        private TreeNode clicknode = null;

        private string TypeName = "刑事罪名";
        string EW_IDText = "";
        int GridViewRowNumber = 0;

        int IsContentOrAddElement = 1;//1为编辑文本0 为编辑要素
        private string FirId = "1000";
        private List<TreeNode> NodeList = new List<TreeNode>();
        public static Color cr;


        #endregion

        private void DataProcess_Load(object sender, EventArgs e)//初始化树
        {
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            DV_AddElement.AutoGenerateColumns = false;
            DV_AddElement.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            //CaseCauseTree();
            CaseCauseTree_Process();


            TypeName = "刑事罪名";
            GetColor();
            //Button sendButton = (Button)sender;
            //sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();

        }

        #region 左侧树

        public void CaseCauseTree()
        {
            #region 初始化
            this.tVCaseCause.Nodes.Clear();
            NodeList = new List<TreeNode>();

            StacticQuery.Text = "";
            CurrNodeNum.Text = "";
            SumQuery.Text = "";
            #endregion

            DataTable dt = trbll.GetCauseTree_Two("", 0);// 第一层

            if (dt.Rows.Count > 0)
            {
                DataRow[] arrayDR = dt.Select("name='" + TypeName + "'");

                foreach (DataRow caseTreeNodeRode in arrayDR)
                {
                    TreeNode node = new TreeNode();

                    node.Text = LdFormat.ObjectToString(caseTreeNodeRode["name"]);
                    node.Tag = caseTreeNodeRode["id"];
                    node.Name = LdFormat.ObjectToString(caseTreeNodeRode["CC_NodeType"].ToString() + "," + caseTreeNodeRode["TableName"].ToString());
                    FirId = caseTreeNodeRode[0].ToString();
                    if (trbll.GetCauseTree_Two(node.Tag.ToString(), 0).Rows.Count > 0)//第二层
                    {
                        node.Nodes.Add(new TreeNode());
                    }
                    tVCaseCause.Nodes.Add(node);
                    NodeList.Add(node);
                }
            }
            if (tVCaseCause.Nodes.Count > 0)
                tVCaseCause.SelectedNode = tVCaseCause.Nodes[0];
        }
        /// <summary>
        /// 显示下一级树节点
        /// </summary>
        /// <param name="parentNode"></param>
        private void CaseCauseTreeChild(TreeNode parentNode)
        {
            DataTable caseTreeNodeRode = GetChild(parentNode);
            if (caseTreeNodeRode.Rows.Count == 0)
                return;
            for (int i = 0; i < caseTreeNodeRode.Rows.Count; i++)//下级
            {

                TreeNode node = new TreeNode();

                node.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["name"]);
                node.Tag = caseTreeNodeRode.Rows[i]["id"];
                node.Name = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CC_NodeType"].ToString() + "," + caseTreeNodeRode.Rows[i]["TableName"].ToString());

                if (clicknode != null && clicknode.FullPath != null)
                {
                    if (clicknode.FullPath.IndexOf("\\单一") > 0 || clicknode.FullPath.IndexOf("\\单一\\") > 0)
                    {
                        DataTable dt;
                        int ismatch = IsMatch.Checked ? 1 : 0;
                        string affirmIdeaResult = IsAffirmIdeaResult.Checked ? "1" : "2";
                        string msid = expresitu.GetES_IDsByCCId(node.Tag.ToString(), ismatch, affirmIdeaResult);
                        dt = wordbll.GetExractContent(msid, sort, IsASC, SelectText, SelectWBK_ID, 0);
                        if (dt == null || dt.Rows.Count == 0)
                        {
                            node.ForeColor = Color.Green;
                        }
                    }
                }
                if (node.Text == "组合" || GetChild(node).Rows.Count > 0)
                {
                    node.Nodes.Add(new TreeNode());
                }
                if (parentNode.Text == "组合" && node.Nodes.Count == 0)
                    continue;
                parentNode.Nodes.Add(node);
                TreeNode node1 = null;
                foreach (var node2 in NodeList)//遍历现在界面上的所有节点
                {
                    if (node2.Tag.ToString() == node.Tag.ToString())
                    {
                        node1 = node2;
                        break;
                    }
                }
                if (node1 != null)
                {
                    NodeList.Remove(node1);
                    NodeList.Add(node);//list用来查询
                }
                else
                {
                    NodeList.Add(node);
                }
            }
        }
        /// <summary>
        /// 获取下一级树节点
        /// </summary>
        /// <param name="parentNode">父节点</param>
        /// <returns></returns>
        private DataTable GetChild(TreeNode parentNode)
        {
            string pid = parentNode.Tag.ToString();
            string pName = parentNode.Text;

            string[] name = parentNode.Name.Split(',');
            int ptype = Convert.ToInt32(name[0]);
            int tableName = Convert.ToInt32(name[1]);
            int childType = trbll.GetChildType(pid, ptype, tableName);//下级改去哪个表查0：CaseCause 1:SYS_Express_GroupSituation
            DataTable caseTreeNodeRode;
            if (childType == 1)
            {

                if (tableName == 0) //如果是第一级 找组合单一
                {
                    int ccIsCombination = 0;
                    SYS_CaseCause model = casecausebLL.GetCaseCauseByCCID(pid);
                    if (model != null && model.CC_IsCombination == 1)
                        ccIsCombination = 1;
                    caseTreeNodeRode = trbll.GetCauseTreeTwo_ToExpressTab_Virtual(pid, ccIsCombination);

                }
                else
                {
                    if (pName == "组合") //如果是组合的，去前缀
                        pid = pid.Substring(1, pid.Length - 1);
                    caseTreeNodeRode = trbll.GetCauseTreeTwo_ToExpressTab(pid, 0);//SYS_Express_GroupSituation 
                }
            }
            else
            {
                if (pName == "单一") //如果是组合的，去前缀
                    pid = pid.Substring(1, pid.Length - 1);
                caseTreeNodeRode = trbll.GetCauseTree_Two(pid, 0); //CaseCause
            }
            return caseTreeNodeRode;

        }

        /// <summary>
        /// 展开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_AfterExpand(object sender, TreeViewEventArgs e)
        {
            //if (e.Node.FirstNode.Tag == null)
            //{
            e.Node.Nodes.Clear();

            CaseCauseTreeChild(e.Node);
            // }
        }

        /// <summary>
        /// 选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_AfterSelect(object sender, TreeViewEventArgs e)
        {
            //if (clicknode != null)
            //{
            //    cr = clicknode.ForeColor;
            //    // clicknode.ForeColor = Color.Black;             
            //}
            clicknode = e.Node;//保存节点

            clicknode.ForeColor = Color.Red;
            //IsAddData = "";
            SelectText = "";
            SelectWBK_ID = "";
            if (clicknode.Text.Contains("（"))
            {
                panel_Attribute.Enabled = false;
            }
            else
            {
                panel_Attribute.Enabled = true;
            }
            dataPagerMain.ChangePageNumber(1);
            ShowRegText();

        }



        /// <summary>
        /// 是否有用情形
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public bool IsUseFul(TreeViewEventArgs e)
        {
            //int type = Convert.ToInt32(e.Node.Name.ToString().Split (',')[0]);
            //if (type == 4 || type == 5 || type == 6 || type == 7 || type == 8)
            //{
            return true;
            //}
            //return false;
        }
        #endregion

        #region 右侧信息列表
        /// <summary>
        /// 列表显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataPagerMain_PageNumberChanging(object sender, Controls.DataPagerPageIndexChangingEventArgs e)
        {
            if (clicknode != null)
            {
                var startRowIndex = e.StartRowIndex;
                //var maximumRows = e.MaximumRows;
                var endRowIndex = e.StartRowIndex + e.MaximumRows;
                DataTable dt;
                string id = clicknode.Tag.ToString();
                //第一种表述节点
                //第二种原SYS_CaseCause节点
                int ismatch = IsMatch.Checked ? 1 : 0;
                string affirmIdeaResult = IsAffirmIdeaResult.Checked ? "1" : "2";
                string msid = expresitu.GetES_IDsByCCId(id, ismatch, affirmIdeaResult);
                int isSingle = 1;
                if (clicknode.FullPath.IndexOf("\\组合\\") > 0) isSingle = 0;

                dt = wordbll.GetExractContent(msid, sort, IsASC, SelectText, SelectWBK_ID, 0);

                //dt = wordbll.GetExractContent(id, msid, isSingle);

                if (dt.Rows.Count > 0)
                {
                    e.TotalCount = dt.Rows.Count;
                    DataTable newdt = new DataTable();
                    newdt = dt.Clone();
                    DataRow[] dr = dt.Select("showindex>" + startRowIndex + " and showindex<=" + endRowIndex);
                    for (int i = 0; i < dr.Length; i++)
                    {
                        newdt.ImportRow((DataRow)dr[i]);
                    }
                    dataGridView1.DataSource = newdt;
                }
                else
                {
                    dataGridView1.DataSource = new DataTable();
                }
            }

        }
        /// <summary>
        /// 转到添加要素界面
        /// </summary>
        private void ToAddWordBanks()
        {
            tabControl1.SelectTab("tabPage2");
            if (null != clicknode)
            {
                linkAddWB.Text = string.Format("<<{0}", clicknode.Text);
            }
            GetWordkeyByCCId();
        }

        /// <summary>
        /// 转到添加要素界面
        /// </summary>
        private void ShowRegText()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ER_Name");
            dt.Columns.Add("ER_OperateType");
            dt.Columns.Add("ER_RegexText");
            string id = clicknode.Tag.ToString();
            id = expresitu.GetES_SituationIdsById(id);
            string regCode = casecausebLL.GetRegCodeByJudgeBook(id);
            IList<Ledict.Regex.Model.Reg_Regex> reglist = getregex.GetRegexs(regCode);
            foreach (Ledict.Regex.Model.Reg_Regex item in reglist)
            {
                DataRow dr = dt.NewRow();
                dr[0] = item.ER_Name;
                switch (item.ER_OperateType)
                {
                    case 1:
                        dr[1] = "提取";
                        break;
                    case 2:
                        dr[1] = "替换";
                        break;
                    case 3:
                        dr[1] = "匹配";
                        break;

                }
                dr[2] = item.ER_RegexText;
                dt.Rows.Add(dr);
            }

            GV_Reg.DataSource = dt;
        }


        /// <summary>
        /// 转到节点树界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            tabControl1.SelectTab("tabPage1");

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DV_AddElement_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 2)  //添加节点重跑数据
            {
                try
                {
                    OpenNodeTree();
                }
                catch (Exception error)
                {

                    MsgBox.Err("添加要素失败!");
                    Log.ErrorLog(error.Message);

                }
            }
            else if (e.ColumnIndex == 0)
            {
                // SelectText  = WhereLike.ToWherelike(DV_AddElement.Rows[e.RowIndex].Cells["Element"].Value.ToString().Replace("\r\n", ""), "EW_Content", 1);  
                SelectWBK_ID = DV_AddElement.Rows[e.RowIndex].Cells["WBK_ID"].Value.ToString();
                SelectText = "";

                dataPagerMain.ChangePageNumber(1);

            }

        }
        private void GetWordkeyByCCId()
        {
            if (clicknode != null)
            {
                string id = clicknode.Tag.ToString();

                //第一种表述节点
                //第二种原SYS_CaseCause节点
                int ismatch = IsMatch.Checked ? 1 : 0;
                string affirmIdeaResult = IsAffirmIdeaResult.Checked ? "1" : "2";
                id = expresitu.GetES_IDsByCCId(id, ismatch, affirmIdeaResult);
                DataTable wordBankKeysdt = wordbll.GetAllwordBankKeys(id);
                DV_AddElement.DataSource = wordBankKeysdt;
            }
        }


        /// <summary>
        /// 编辑列表（单击）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                #region 对勾和差
                if (e.ColumnIndex == 7 || e.ColumnIndex == 8)
                {
                    DataGridViewCheckBoxCell checkCellRight = (DataGridViewCheckBoxCell)dataGridView1.Rows[e.RowIndex].Cells["Right"];
                    DataGridViewCheckBoxCell checkCellwrong = (DataGridViewCheckBoxCell)dataGridView1.Rows[e.RowIndex].Cells["wrong"];
                    if (e.ColumnIndex == 7)
                    {
                        if (Convert.ToBoolean(checkCellRight.Value) == true)
                        {
                            checkCellRight.Value = false;
                            checkCellwrong.Value = true;
                        }
                        else
                        {
                            checkCellRight.Value = true;
                            checkCellwrong.Value = false;
                        }

                    }
                    if (e.ColumnIndex == 8)
                    {
                        if (Convert.ToBoolean(checkCellwrong.Value) == true)
                        {
                            checkCellRight.Value = true;
                            checkCellwrong.Value = false;
                        }
                        else
                        {
                            checkCellRight.Value = false;
                            checkCellwrong.Value = true;
                        }
                    }

                    SYS_Express_Word model = new SYS_Express_Word();
                    model.EW_Right = Convert.ToInt32(checkCellRight.Value);
                    model.EW_Wrong = Convert.ToInt32(checkCellwrong.Value);
                    model.EW_ID = dataGridView1.Rows[e.RowIndex].Cells["EW_ID"].Value.ToString();

                    wordbll.UpdateChooseState_Process(model);
                    if (model.EW_Right == 1)//添加到表述库加工
                    {
                        model = wordbll.GetModel_Process(dataGridView1.Rows[e.RowIndex].Cells["EW_ID"].Value.ToString());

                        UpdateCC_IsShowExpress(clicknode);

                        if (!wordbll.Exists_Word(model))
                        {
                            wordbll.Add_Word(model);//添加word 表
                        }
                    }
                }

                #endregion
                if (e.ColumnIndex == 2)  //编辑文本
                {

                    EW_IDText = dataGridView1.Rows[e.RowIndex].Cells["EW_ID"].Value.ToString();

                    textBox1.Text = "";
                    textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells["EW_Content"].Value.ToString();
                    //byte[] buffer = Encoding.UTF8.GetBytes(dataGridView1.Rows[e.RowIndex].Cells["EW_Content"].Value.ToString());
                    //textBox1.Text = Encoding.GetEncoding("UTF-8").GetString(buffer);
                    GridViewRowNumber = e.RowIndex;
                    ColorWord();

                }

            }

        }

        /// <summary>
        /// 自己和所有父级节点记状态
        /// </summary>
        /// <param name="nowNode"></param>
        private void UpdateCC_IsShowExpress(TreeNode nowNode)
        {

            wordbll.UpdateCC_IsShowExpress(nowNode.Tag.ToString(), 1);
            if (nowNode.Parent != null)
                UpdateCC_IsShowExpress(nowNode.Parent);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Delete_Click(object sender, EventArgs e)
        {
            string DeleteID = "";
            int num = 0;
            for (var i = 0; i <= dataGridView1.Rows.Count - 1; i++)
            {
                var check = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells["Column1"];
                if (Convert.ToBoolean(check.Value))
                {
                    num++;
                }
            }
            if (num == 0)
            {
                MsgBox.Warn("请勾选需要删除的数据后再试");
                return;
            }
            if (MessageBox.Show("确认要删除数据吗？", "此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    bool res = false;
                    for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
                    {
                        DataGridViewCheckBoxCell check = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells["Column1"];
                        if (Convert.ToBoolean(check.Value) == true)
                        {
                            DeleteID = dataGridView1.Rows[i].Cells["EW_ID"].Value.ToString();
                            if (DeleteID != "")
                            {

                                res = wordbll.Delete_WordProcess(DeleteID);
                            }

                        }
                    }
                    if (res)
                    {
                        MsgBox.OK("删除成功!");
                    }
                    else
                    {
                        MsgBox.Warn("删除失败!");
                    }
                }
                catch (Exception error)
                {
                    MsgBox.Err("删除失败!");
                    Log.ErrorLog(error.Message);

                }
                dataPagerMain.ChangePageNumber(1);
            }
        }



        /// <summary>
        /// 2017年5月15日 ljj-update 方法从未被使用
        /// 显示窗体，自动将窗体填满父窗体的工作区
        /// </summary>
        /// <param name="childForm"></param>
        //private void ShowForm(Form childForm)
        //{
        //    childForm.MdiParent = this.MdiParent;
        //    childForm.StartPosition = FormStartPosition.CenterParent;
        //    childForm.Show();
        //    childForm.Activate();
        //    childForm.Dock = DockStyle.Fill;
        //    var size = childForm.Size;
        //    var location = childForm.Location;
        //    childForm.Dock = DockStyle.None;
        //    childForm.Size = size;
        //    childForm.Location = location;
        //}
        /// <summary>
        /// 修改文本 
        /// </summary>=""
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateWord_Click(object sender, EventArgs e)
        {
            if (IsContentOrAddElement == 1)
            {
                if (wordbll.UpdateContent(EW_IDText, textBox1.Text))
                {
                    MessageBox.Show("修改成功!");
                }
                else
                {
                    MessageBox.Show("修改失败!");
                }

                if (dataGridView1.Rows.Count > 0)
                {
                    DataGridViewCell checkCellwrong = (DataGridViewCell)dataGridView1.Rows[GridViewRowNumber].Cells["EW_Content"];
                    checkCellwrong.Value = textBox1.Text;
                }
            }

        }
        #endregion

        #region 多线程

        WorkThread workObj = new WorkThread();
        //工作对象
        private Thread workThread;





        //暂停(只针对第一次加工数据)
        private void Endbtn_Click(object sender, EventArgs e)
        {
            if (workThread != null)
            {
                workThread.Abort();
                workThread = null;
            }
        }

        // 显示进度条
        public void ShowProgress(int maxCount, int currentCount)
        {
            if (this.progressBar1.InvokeRequired == false)
            {
                if (currentCount < maxCount)
                {
                    progressBar1.Value = currentCount;
                    progressBar1.Maximum = maxCount;
                    progressBar1.Text = currentCount + "/" + maxCount;
                    label1.Text = string.Format("当前{0}条|总共{1}条", currentCount, maxCount);
                }
                else if (currentCount == maxCount)
                {
                    progressBar1.Value = currentCount;
                    progressBar1.Maximum = maxCount;
                    progressBar1.Text = currentCount + "/" + maxCount;
                    label1.Text = string.Format("已完成，共{0}条", maxCount);
                    workThread = null;
                    StaticCacheBLL.plotchildDict = new Dictionary<string, DataTable>();//清除规则缓存
                }
            }
            else
            {
                ProcessShow processshow = new ProcessShow(ShowProgress);
                this.Invoke(processshow, new object[] { maxCount, currentCount });
            }

        }


        /// <summary>
        /// 开始执行线程
        /// </summary>
        //private void ThreadExecute(DataSourceCondition condi, string luceneSearchType)
        //{
        //    if (!string.IsNullOrEmpty(luceneSearchType))
        //    {
        //        //  workThread = null;
        //        workObj.processShow = ShowProgress;
        //        workObj.closeForm = CloseForm;
        //        workObj.conditon = condi;

        //        workObj.LuceneSearchType = luceneSearchType.ToUpper();//设置查询lucene方法

        //        //workThread = new Thread(workObj.execute_Start);
        //        workThread = new Thread(workObj.execute_Start);
        //        workThread.Start();
        //    }
        //}


        #endregion

        #region  加工条件
        /// <summary>
        /// 开始加工(组织条件)第一次加工
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 
        private void StartBtn_Click(object sender, EventArgs e)
        {
            try
            {
                //先根据ID去获取该案由实体
                SYS_CaseCause objCaseCause = casecausebLL.GetCaseCauseByCCID(NowProcessNode.Text.Trim());
                if (objCaseCause != null && !string.IsNullOrEmpty(objCaseCause.CC_Name))
                {
                    //if (MsgBox.Ask("" + objCaseCause.CC_Name + "(" + NowProcessNode.Text + ")" + "下已经存在表述节，是否先删除？选择是将想删除然后在开始执行") == DialogResult.Yes)
                    //{
                    //    if (wordbll.DeleteSYS_Express_Word_Process(NowProcessNode.Text.Trim()) && express_matchsituationbll.DeleteSYS_Express_MatchSituation(NowProcessNode.Text.Trim()))
                    //    {
                    int count = CaseCauseCondDAL.GetExpressCount(objCaseCause.CC_ID);
                    if (count > 0)
                    {
                        if (workThread == null)//创建线程
                        {
                            workObj = WorkThreadFactory.CreateWorkThreadObj("WorkThread_first_CrimeNew");
                            workObj.conditon = new DataSourceCondition();
                            workObj.conditon.SituationId = objCaseCause.CC_ID;
                            workObj.processShow = ShowProgress;
                            workObj.closeForm = CloseForm;


                            workThread = new Thread(workObj.execute_Start);
                            workThread.Start();
                            label1.Text = "开始处理数据...";
                        }
                        else//暂停后重启
                        {
                            MsgBox.Warn("当前操作未完成，请等待");
                            // workObj.Resume();
                        }
                        //    }
                        //}
                    }
                    else
                    {
                        MsgBox.Warn("当前案由节点下不存在需要处理的数据!");
                    }
                }
                else
                {
                    MsgBox.Warn("不存在该案由节点，请重新填写!");
                }
            }
            catch (Exception ex)
            {
                MsgBox.Err("系统报错，请查看错误日志!");

                Log.ErrorLog(ex.Message);
            }
        }

        #region  重加工
        /// <summary>
        /// 重跑数据开始(立即处理)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Start_Again(Dictionary<string, string> AddEleDic)
        {

            //workObj = WorkThreadFactory.CreateWorkThreadObj("second");

            //NodeTree ae = NodeTree.Default;
            //if (ae.LocateNode != "")
            //{
            //    ae.Close();
            //}

            //StringBuilder elements = new StringBuilder();

            //foreach (KeyValuePair<string, string> kv in AddEleDic)//一个一个开始
            //{
            //    #region 查询条件

            //    DataSourceCondition condi = new DataSourceCondition(); //条件
            //    condi.ISAgainData = true;
            //    condi.SituationId = kv.Key;
            //    conditonList.Add(condi);
            //    #endregion

            //}
            //Threadexecute();
        }

        /// <summary>
        /// 开始处理"暂不处理"的要素（稍后处理）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExecAllStart_Click(object sender, EventArgs e)
        {
            //workObj = WorkThreadFactory.CreateWorkThreadObj("second");
            //conditonList.Clear();

            //DataTable AllElem = addelementbll.GetAllElement();

            //for (int i = 0; i < AllElem.Rows.Count; i++)
            //{

            //    #region 查询条件

            //    DataSourceCondition condi = new DataSourceCondition(); //条件
            //    condi.ISAgainData = true;
            //    condi.SituationId = AllElem.Rows[i]["StiuatonId"].ToString();
            //    conditonList.Add(condi);
            //    #endregion

            //}
            //// workObj

            //Threadexecute();

            ////清库
            //wordbll.UpdateClearElement_Process();
        }


        /// <summary>
        /// 保存"暂不处理"的要素（稍后处理）
        /// </summary>
        /// <param name="AddEleDic"></param>
        public void SaveElement(Dictionary<string, string> AddEleDic)
        {
            //ConditionExtract.NodeTree ae = ConditionExtract.NodeTree.Instance;
            //if (ae.LocateNode != "")
            //{
            //    ae.Close();
            //}

            //StringBuilder elements = new StringBuilder();
            //foreach (KeyValuePair<string, string> kv in AddEleDic)
            //{
            //    addelementbll.AddExpress_AddElement(kv.Key, kv.Value);
            //    elements.Append("," + kv.Value);
            //}

            //wordbll.UpdateAddElement_Process(EW_IDText, elements.ToString());
            //dataPagerMain.ChangePageNumber(dataPagerMain._currentPageNumber);
        }


        #endregion

        #endregion

        #region 小功能（刷新关闭 有问题）


        bool closeState = false;
        //关闭
        private void DataProcess_FormClosing(object sender, FormClosingEventArgs e)
        {

            if (workThread != null && workThread.IsAlive && e.CloseReason == CloseReason.UserClosing && !closeState)
            {
                workObj.Stop();

                e.Cancel = true;
            }

        }
        public void CloseForm()
        {
            if (this.progressBar1.InvokeRequired == false)
            {
                closeState = true;
                Close();
            }
            else
            {
                CloseForm closeForm = new CloseForm(CloseForm);
                this.Invoke(closeForm);
            }
        }
        //刷新
        private void button3_Click(object sender, EventArgs e)
        {
            CaseCauseTree();
        }
        #endregion

        #region 界面显示（非核心功能）

        #region 查询节点(有问题)
        DataTable Querydt;
        private void QueryNodeTxt_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                QueryNode();
            }

        }

        /// <summary>
        /// 查询
        /// </summary>
        private void QueryNode()
        {
            tVCaseCause.SelectedNode.ForeColor = Color.Black;
            string queryNodeName = QueryNodeTxt.Text.Trim();

            if (queryNodeName != "")
            {
                Querydt = trbll.NodeTree_Query(FirId, queryNodeName, 2);
                StacticQuery.Text = Querydt.Rows.Count.ToString();
                if (Querydt.Rows.Count > 0)
                {
                    CurrNodeNum.Text = "1";
                    SumQuery.Text = CurrNodeNum.Text;
                    int currNode = Convert.ToInt32(CurrNodeNum.Text);
                    LinkIsVisible(currNode);
                    QueryNode_Page(Querydt, currNode);
                }
                else
                {
                    CurrNodeNum.Text = "0";
                    SumQuery.Text = CurrNodeNum.Text;
                    MessageBox.Show("没有查询到结果！");
                }
            }
            else
            {
                MessageBox.Show("请输入关键字！");
            }
        }




        private void QueryNodeBtn_Click(object sender, EventArgs e)//查询
        {
            QueryNode();
        }
        /// <summary>
        /// 下一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Nextlinkbtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (!string.IsNullOrEmpty(CurrNodeNum.Text))
            {
                CurrNodeNum.Text = (Convert.ToInt32(CurrNodeNum.Text) + 1).ToString();
                SumQuery.Text = CurrNodeNum.Text;
                int CurrNode = Convert.ToInt32(CurrNodeNum.Text);
                QueryNode_Page(Querydt, CurrNode);
                LinkIsVisible(CurrNode);
            }
        }
        /// <summary>
        /// 上一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Prelinkbtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (!string.IsNullOrEmpty(CurrNodeNum.Text))
            {
                CurrNodeNum.Text = (Convert.ToInt32(CurrNodeNum.Text) - 1).ToString();
                SumQuery.Text = CurrNodeNum.Text;
                int CurrNode = Convert.ToInt32(CurrNodeNum.Text);
                QueryNode_Page(Querydt, CurrNode);
                LinkIsVisible(CurrNode);
            }
        }
        /// <summary>
        /// 查询分页
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="showindex"></param>
        private void QueryNode_Page(DataTable dt, int showindex)
        {
            if (dt.Rows.Count >= showindex)
            {
                string[] NotePidArr = trbll.GetAllParentNode(dt.Rows[showindex - 1]["id"].ToString()).Split(',');
                for (int i = 0; i < NotePidArr.Length; i++)
                {

                    if (i != NotePidArr.Length - 1)
                    {
                        var Node = FindNode(NotePidArr[i]);
                        if (Node != null)
                        {
                            Node.Expand();//拖出所有父级节点
                        }
                    }
                    else
                    {
                        TreeNode node = FindNode(NotePidArr[i]);
                        this.tVCaseCause.SelectedNode = node;

                    }
                }
            }
            else
            {
                MessageBox.Show("跳转页码有误，重新输入！");
            }


        }
        /// <summary>
        /// 找到节点
        /// </summary>
        /// <param name="Nodeid"></param>
        /// <returns></returns>
        private TreeNode FindNode(string Nodeid)
        {
            foreach (TreeNode node in NodeList)
            {
                if (node.Tag.ToString() == Nodeid)
                {
                    return node;
                }
            }
            return null;

        }
        /// <summary>
        /// 上一条下一条是否可用
        /// </summary>
        /// <param name="CurrNode"></param>
        private void LinkIsVisible(int CurrNode)
        {
            Prelinkbtn.Enabled = true;
            Nextlinkbtn.Enabled = true;
            if (CurrNode <= 1)
            {
                Prelinkbtn.Enabled = false;
            }
            if (CurrNode >= Querydt.Rows.Count)
            {
                Nextlinkbtn.Enabled = false;
            }




        }
        /// <summary>
        /// 跳页查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GoQuery_Click(object sender, EventArgs e)
        {
            int CurrNode = Convert.ToInt32(SumQuery.Text);

            if (Querydt.Rows.Count >= CurrNode)
            {
                CurrNodeNum.Text = SumQuery.Text;
                QueryNode_Page(Querydt, CurrNode);
                LinkIsVisible(CurrNode);
            }
            else
            {
                MessageBox.Show("跳转页码有误，重新输入！");
            }

        }

        #endregion

        public void GetTreeHeadWordsChild(TreeNode parentNode, string Tname)
        {
            DataTable dt = trbll.GetTreeHeadWords(parentNode.Tag.ToString(), Tname);// 第一层
            DataRow[] arrayDR = dt.Select();

            foreach (DataRow CaseTreeNodeRode in arrayDR)
            {
                TreeNode node = new TreeNode();

                node.Text = LdFormat.ObjectToString(CaseTreeNodeRode["name"]) + "(" + CaseTreeNodeRode["id"] + ")";
                node.Tag = CaseTreeNodeRode["id"];
                //判断是否有子节点
                if (trbll.GetTreeHeadWords(node.Tag.ToString(), Tname).Rows.Count > 0)//第二层
                {
                    node.Nodes.Add(new TreeNode());
                }
                parentNode.Nodes.Add(node);

            }

        }

        public void t_Case_HeadWords_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            GetTreeHeadWordsChild(e.Node, "t_Case_HeadWords");
        }
        public void t_Global_Court_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            GetTreeHeadWordsChild(e.Node, "t_Global_Court");
        }
        #endregion

        #region 刑事民事行政按钮(显示不同树)
        public void GetColor()
        {
            //button8.BackColor = Color.White;
            //button6.BackColor = Color.White;
            //button5.BackColor = Color.White;
            //button4.BackColor = Color.White;
            //button7.BackColor = Color.White;
        }
        private void button8_Click(object sender, EventArgs e)
        {

        }

        private void button6_Click(object sender, EventArgs e)
        {
            TypeName = "民事案由";
            GetColor();
            Button sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            TypeName = "行政案由";
            GetColor();
            Button sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            TypeName = "赔偿案由";
            GetColor();
            Button sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            TypeName = "执行案由";
            GetColor();
            Button sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        #endregion

        #region 各种排序(字长、数目)

        private void SelectAdd_Click(object sender, EventArgs e)
        {
            if (txt_SelectWord.Text.Trim() != "")
                SelectText = WhereLike.ToWherelike(txt_SelectWord.Text.Trim(), "EW_Content", 1);
            else
                SelectText = "";

            dataPagerMain.ChangePageNumber(1);
        }

        private void SelectCut_Click(object sender, EventArgs e)
        {
            if (txt_SelectWord.Text.Trim() != "")
                SelectText = WhereLike.ToWherelike(txt_SelectWord.Text.Trim(), "EW_Content", 0);
            else
                SelectText = "";
            dataPagerMain.ChangePageNumber(1);
        }


        private void WordLengSort_Click(object sender, EventArgs e)
        {
            sort = "WordLengSort";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);
        }

        private void AlphabetSort_Click(object sender, EventArgs e)
        {
            sort = "AlphabetSort";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);
        }

        private void CountSort_Click(object sender, EventArgs e)
        {
            sort = "CountSort";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);
        }

        private void ISCheckSort_Click(object sender, EventArgs e)
        {
            sort = "RightSort";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);


        }

        private void NotCheckSort_Click(object sender, EventArgs e)
        {

        }
        private void IsMatch_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
            SelectText = "";
            SelectWBK_ID = "";
            if (tabControl1.SelectedIndex == 1)
            {
                ToAddWordBanks();
            }
        }

        private void NotMatch_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
            SelectText = "";
            SelectWBK_ID = "";
            if (tabControl1.SelectedIndex == 1)
            {
                ToAddWordBanks();
            }
        }

        private void IsAffirmIdeaResult_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
            SelectText = "";
            SelectWBK_ID = "";
            if (tabControl1.SelectedIndex == 1)
            {
                ToAddWordBanks();
            }
        }

        private void NotAffirmIdeaResult_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
            if (tabControl1.SelectedIndex == 1)
            {
                ToAddWordBanks();
            }
        }



        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            AddWordBank();
        }

        private void button9_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows[GridViewRowNumber].Cells["EW_ID"] != null)
            {
                AddWordBank();
                EW_IDText = dataGridView1.Rows[GridViewRowNumber].Cells["EW_ID"].Value.ToString();
                textBox1.Text = "";
                textBox1.Text = dataGridView1.Rows[GridViewRowNumber].Cells["EW_Content"].Value.ToString();
                ColorWord();
            }
        }

        private void AddWordBank()
        {
            try
            {
                SYS_WordBank_KeyWords model = new SYS_WordBank_KeyWords();
                string addelement = textBox1.SelectedText;
                string[] wordsTextArr = addelement.Split(',', '，', ';', '；');
                foreach (var item in wordsTextArr)
                {
                    if (item != "")
                    {
                        DataTable dt = wordbankbll.GetWB_IDByHeadword(clicknode.Tag.ToString());
                        if (dt.Rows.Count > 0)
                            model.WB_ID = dt.Rows[0]["WB_ID"].ToString();
                        else
                            model.WB_ID = clicknode.Tag.ToString();
                        model.WBK_Word = item;
                        model.WBK_Length = item.Length;
                        wordbankkeywordsbll.Add(model);
                    }
                }


                MsgBox.OK("添加词库成功！");
            }
            catch (Exception error)
            {
                MsgBox.Err("添加词库失败！");
                Log.ErrorLog(error.Message);

            }

        }

        /// <summary>
        /// 标红词库
        /// </summary>
        private void ColorWord()
        {
            #region 标红词库
            textBox1.SelectionBackColor = Color.White;

            string EW_ID = dataGridView1.Rows[GridViewRowNumber].Cells["EW_ID"].Value.ToString();
            //string MS_ID = dataGridView1.Rows[GridViewRowNumber].Cells["MS_ID"].Value.ToString();
            IsContentOrAddElement = 1;

            DataTable dt = express_wordbankrelbll.Get_Express_WordBankRel(EW_ID);

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                StateWord(dt.Rows[i]["WBK_Word"].ToString());

            }

            #endregion
        }

        private void StateWord(string SelectWord)
        {

            textBox1.SelectionStart = 0;
            textBox1.SelectionLength = textBox1.Text.Length;

            System.Text.RegularExpressions.MatchCollection mc;
            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(SelectWord); //定义一个Regex对象实例
            mc = r.Matches(textBox1.Text);
            for (int i = 0; i < mc.Count; i++) //在输入字符串中找到所有匹配
            {
                int start = mc[i].Index; //记录匹配字符的位置
                int length = (SelectWord).Length;
                textBox1.SelectionStart = start;
                textBox1.SelectionLength = length;
                textBox1.SelectionBackColor = Color.Red;
            }
        }

        #region 添加表述
        /// <summary>
        /// 添加表述
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddExpressWprd_Click(object sender, EventArgs e)
        {
            try
            {
                string ccId = clicknode.Tag.ToString();
                string caseid = "1000000";
                string ParagraphID = "150";
                string resultText = textBox1.Text;
                if (casecausebLL.GetSYS_CaseCauseByCCID(ccId).Rows.Count > 0)//单一节点
                {
                    DataTable processNodedt = work.BelongCaseCauseId(ccId);//节点匹配数据开始处
                    if (processNodedt.Rows.Count > 0)
                    {
                        work.AddToExpress(resultText, caseid, ParagraphID, processNodedt.Rows[0]["CC_ID"].ToString(), ccId);
                    }
                    else
                    {
                        MsgBox.Warn("添加失败,未找到符合条件的根节点");
                        return;
                    }
                }
                else//组合节点
                {
                    #region 添加文本
                    SYS_Express_Word WordModel = new SYS_Express_Word();
                    WordModel.MS_ID = ccId;
                    WordModel.EW_CaseId = caseid;
                    WordModel.EW_Content = resultText;
                    WordModel.EW_UseCount = 1;
                    WordModel.EW_WordCount = resultText.Length;
                    WordModel.ParagraphTypeId = Convert.ToInt32(ParagraphID);
                    WordModel.EW_IsSingleExpress = 0;
                    WordModel.EW_ID = wordbll.Exists_WordProcess(WordModel);
                    if (WordModel.EW_ID == "")
                    {
                        WordModel.EW_ID = newid.JudgeDoc_CreateID("SYS_Express_Word");
                        WordModel.EW_Right = 0;
                        WordModel.EW_Wrong = 0;
                        wordbll.AddWord_Process(WordModel);
                    }
                    else
                    {
                        wordbll.UpdateWord_Process(WordModel);
                    }
                    #endregion

                    #region 词库
                    List<string> EW_AddElementStr = express_wordbankrelbll.WordBank("", WordModel.EW_Content);
                    foreach (var item in EW_AddElementStr)
                    {
                        if (!express_wordbankrelbll.Exists(WordModel.EW_ID, item))
                        {
                            express_wordbankrelbll.Add_Express_WordBankRel(newid.JudgeDoc_CreateID("SYS_Express_WordBankRel"), WordModel.EW_ID, item);
                        }
                    }
                    #endregion
                }
                dataPagerMain.ChangePageNumber(dataPagerMain._currentPageNumber);
                textBox1.Text = "";
                MessageBox.Show("添加表述成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show("添加表述失败！");
                Log.ErrorLog(ex.ToString());
            }
        }
        #endregion



        private void button10_Click(object sender, EventArgs e)
        {
            OpenNodeTree();
        }

        private void OpenNodeTree()
        {
            if (clicknode != null)
            {
                //ConditionExtract.NodeTree nt1 = ConditionExtract.NodeTree.Instance;
                //nt1.Close();
                ConditionExtract.NodeTree nt =new ConditionExtract.NodeTree();
                ConditionExtract.NodeTree.TypeName = TypeName;
                nt.FirId = FirId;
                nt.LocateNode = expresitu.GetES_SituationIdsById(clicknode.Tag.ToString());
                if (nt.LocateNode.Contains(","))
                {
                    nt.LocateNode = nt.LocateNode.Substring(0, nt.LocateNode.IndexOf(","));
                }
            ((MainForm)this.Parent.Parent).ShowForm(nt);
            }
        }

        private void button11_Click(object sender, EventArgs e)
        {
            ToAddWordBanks();
        }
        private TreeNode editnode = null;//点击获得当前节点
        private void tVCaseCause_MouseDown(object sender, MouseEventArgs e)
        {
            Point ClickPoint = new Point(e.X, e.Y);
            editnode = tVCaseCause.GetNodeAt(ClickPoint);
            if (editnode != null)//判断你点的是不是一个节点
            {
                editnode.ContextMenuStrip = contextMenuStrip1;
            }
        }
        private void 添加要素ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ToAddWordBanks();
        }
        private void AddNodeMenuItem_Click(object sender, EventArgs e)
        {
            group_add.Visible = true;

        }


        private void btn_quit_Click(object sender, EventArgs e)
        {
            group_add.Visible = false;
            TxtCC_ID.Text = "";
            IsMatch2.Checked = true;
            IsAffirmIdeaResult2.Checked = true;
            MatchSource.Text = "0";
            AffirmIdeaSource.Text = "0";
        }

        /// <summary>
        /// 添加节点（只能在组合下添加）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_add_Click(object sender, EventArgs e)
        {
            var newModel = new SYS_Express_MatchSituation();
            string ccId = TxtCC_ID.Text;
            newModel.IsMatch = IsMatch2.Checked ? 1 : 0;
            newModel.MatchSource = MatchSource.Text;
            newModel.AffirmIdeaResult = IsAffirmIdeaResult2.Checked ? "1" : "2";
            newModel.AffirmIdeaSource = AffirmIdeaSource.Text;

            string MS_ID = dataprocess_editnode.AddNode(ccId, editnode.Tag.ToString(), newModel);
            //添加完以后界面显示
            if (MS_ID != "")
            {
                MessageBox.Show("添加成功！");
                newModel = express_matchsituationbll.GetMatchSituation(MS_ID);
                clicknode.Expand();
                TreeNode addnode = new TreeNode();
                addnode.Tag = newModel.MS_ID;
                addnode.Text = newModel.SituationName;
                addnode.Name = newModel.SituationType.ToString();
                clicknode.Nodes.Add(addnode);
            }
            else
            {
                MessageBox.Show("添加失败，节点只能在组合部分添加！");
            }
            group_add.Visible = false;
        }


        #region 情形情节树(条件)

        /// <summary>
        /// 树（第一级）
        /// </summary>
        public void CaseCauseTree_Process()
        {
            DataTable dt = trbll.NodeTree_Tree("");
            DataRow[] arrayDR = dt.Select("name='" + "刑事罪名" + "'");

            foreach (DataRow caseTreeNodeRode in arrayDR)
            {
                var node = new TreeNode
                {
                    Text =
                        LdFormat.ObjectToString(caseTreeNodeRode[1]) + "(" +
                        LdFormat.ObjectToString(caseTreeNodeRode[0]) + ")",
                    Tag = caseTreeNodeRode[0],
                    Name = LdFormat.ObjectToString(caseTreeNodeRode[2])
                };

                FirId = caseTreeNodeRode[0].ToString();
                if (trbll.NodeTree_Tree(node.Tag.ToString()).Rows.Count > 0)
                {
                    node.Nodes.Add(new TreeNode());
                }
                NowProcessNode.TreeView.Nodes.Add(node);
            }
        }
        /// <summary>
        /// 下级树
        /// </summary>
        /// <param name="parentNode"></param>
        private void CaseCauseTreeChild_Process(TreeNode parentNode)
        {
            string pid = parentNode.Tag.ToString();
            DataTable caseTreeNodeRode = trbll.NodeTree_Tree(pid);
            if (caseTreeNodeRode.Rows.Count == 0)
                return;
            for (int i = 0; i < caseTreeNodeRode.Rows.Count; i++)
            {
                var node = new TreeNode
                {
                    Text = caseTreeNodeRode.Rows[i]["name"] + @"(" + caseTreeNodeRode.Rows[i]["id"] + @")",
                    Tag = caseTreeNodeRode.Rows[i]["id"],
                    Name = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CC_NodeType"])
                };


                if (trbll.NodeTree_Tree(node.Tag.ToString()).Rows.Count > 0)
                {
                    node.Nodes.Add(new TreeNode());
                }
                parentNode.Nodes.Add(node);
            }
        }

        private void NowProcessNode_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            CaseCauseTreeChild_Process(e.Node);
        }

        #endregion

        private void GV_Reg_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                OpenNodeTree();
            }
        }


        private void AgainOrganTree_Click(object sender, EventArgs e)
        {
            //if (workThread == null)//创建线程
            //{
            //    #region 查询条件

            //    DataSourceCondition condi = new DataSourceCondition(); //条件
            //    #endregion

            //    workObj = WorkThreadFactory.CreateWorkThreadObj("WorkThread_Order");
            //    ThreadExecute(condi, null);

            //}

        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 全部展开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 全部展开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AllExpandNode(editnode.Tag.ToString());//展开全部
        }

        /// <summary>
        /// 展开全部
        /// </summary>
        /// <param name="pid"></param>
        private void AllExpandNode(string pid)
        {

            var findNode = FindNode(pid);
            if (findNode != null) findNode.ExpandAll();

            //DataTable caseTreeNodeRode = trbll.NodeTree_Tree(pid);//父级ID的下级节点
            //if (caseTreeNodeRode.Rows.Count == 0)
            //    return;
            //for (int i = 0; i < caseTreeNodeRode.Rows.Count; i++)
            //{
            //    TreeNode node = new TreeNode();
            //    node.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["name"]);
            //    node.Tag = caseTreeNodeRode.Rows[i]["id"];
            //    node.Name = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CC_NodeType"]);
            //    AllExpandNode(node.Tag.ToString());
            //}
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            SYS_CaseCause objCaseCause = casecausebLL.GetCaseCauseByCCID(NowProcessNode.Text.Trim());
            if (objCaseCause != null && !string.IsNullOrEmpty(objCaseCause.CC_Name))
            {
                if (MsgBox.Ask("是否删除" + objCaseCause.CC_Name + "(" + NowProcessNode.Text + ")" + "下的表述节点及其表述内容？") == DialogResult.Yes)
                {
                    //express_matchsituationbll.DeleteSYS_Express_MatchSituation(NowProcessNode.Text.Trim());
                    if (wordbll.DeleteSYS_Express_Word_Process(NowProcessNode.Text.Trim()) && express_matchsituationbll.DeleteSYS_Express_MatchSituation(NowProcessNode.Text.Trim()))
                    {
                        MessageBox.Show("删除成功！");
                    }
                    else
                    {
                        MessageBox.Show("删除失败！");
                    }
                }
            }
            else
            {
                MessageBox.Show("请先选择处理节点！");
            }
        }

        private void tVCaseCause_MouseDown_1(object sender, MouseEventArgs e)
        {
            Point ClickPoint = new Point(e.X, e.Y);
            editnode = tVCaseCause.GetNodeAt(ClickPoint);
            if (editnode != null)//判断你点的是不是一个节点
            {
                editnode.ContextMenuStrip = contextMenuStrip1;
                if (clicknode != null && clicknode.FullPath.IndexOf("\\单一\\") > 0)
                {
                    DataTable dt;
                    int ismatch = IsMatch.Checked ? 1 : 0;
                    string affirmIdeaResult = IsAffirmIdeaResult.Checked ? "1" : "2";
                    string msid = expresitu.GetES_IDsByCCId(clicknode.Tag.ToString(), ismatch, affirmIdeaResult);
                    dt = wordbll.GetExractContent(msid, sort, IsASC, SelectText, SelectWBK_ID, 0);
                    if (dt == null || dt.Rows.Count == 0)
                    {
                        clicknode.ForeColor = Color.Green;
                    }
                    else
                    {
                        clicknode.ForeColor = Color.Black;
                    }
                }
                else
                {
                    clicknode.ForeColor = Color.Black;
                }
                clicknode = editnode;
            }
        }

        /// <summary>
        /// 添加要素
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 添加要素ToolStripMenuItem1_Click_1(object sender, EventArgs e)
        {
            ToAddWordBanks();
        }

        /// <summary>
        /// 添加子节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddNodeMenuItem_Click_1(object sender, EventArgs e)
        {
            group_add.Visible = true;
        }

        /// <summary>
        /// 全部展开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 全部展开ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            AllExpandNode(editnode.Tag.ToString());//展开全部
        }
    }
}
